package com.mnyc.research.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.mnyc.common.utils.DateUtils;
import com.mnyc.common.utils.SecurityUtils;
import com.mnyc.research.domain.JyActivityTeacher;
import com.mnyc.research.domain.JyActivityTeacherRela;
import com.mnyc.research.domain.JyTeacher;
import com.mnyc.research.mapper.JyActivityTeacherMapper;
import com.mnyc.research.mapper.JyActivityTeacherRelaMapper;
import com.mnyc.research.service.IJyActivityTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 人员记录主Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-08
 */
@Service
public class JyActivityTeacherServiceImpl implements IJyActivityTeacherService {
    @Autowired
    private JyActivityTeacherMapper mapper;
    @Autowired
    JyActivityTeacherRelaMapper relaMapper;

    /**
     * 查询一个活动对应人员
     *
     * @param activityId   活动Id
     * @param activityType 活动类型
     * @param userType     人员类型
     */
    @Override
    public List<JyActivityTeacherRela> getActivityUser(Long activityId, String activityType, String userType) {
        JyActivityTeacher mainInfo = mapper.selectByActivityIdAndType(activityId, activityType);
        if (mainInfo != null) {
            return relaMapper.selectRelaListByMainIdAndType(mainInfo.getId(), mainInfo.getActivityType());
        }
        return Collections.emptyList();
    }

    @Transactional
    @Override
    public void insertActivityUser(Long activityId, String activityType, String userType, List<JyActivityTeacherRela> relaList) {
        JyActivityTeacher mainInfo = mapper.selectByActivityIdAndType(activityId, activityType);
        if (mainInfo == null) {
            mainInfo = new JyActivityTeacher();
            mainInfo.setActivityId(activityId);
            mainInfo.setActivityType(activityType);
            mainInfo.setCreateBy(SecurityUtils.getUsername());
            mainInfo.setCreateTime(DateUtils.getNowDate());
            mapper.insertJyActivityTeacher(mainInfo);
        }
        relaMapper.delleteByMainIdAndType(mainInfo.getId(), userType);
        if (CollUtil.isNotEmpty(relaList)) {
            for (JyActivityTeacherRela rela : relaList) {
                rela.setMainId(mainInfo.getId());
                rela.setType(userType);
                rela.setCreateBy(SecurityUtils.getUsername());
                rela.setCreateTime(DateUtils.getNowDate());
            }
            relaMapper.batchInsertRela(relaList);
        }

    }
}
